package com.starlink.advice;

import com.google.common.collect.Lists;
import com.starlink.common.WebResponse;
import com.starlink.common.enums.ErrorCode;
import com.starlink.common.exception.BusinessException;
import com.starlink.common.exception.BusinessNotLoginException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * @author zhanghong
 */
@Slf4j
@RestControllerAdvice(annotations = RestController.class)
public class ControllerAdvice {

    @ExceptionHandler({BusinessNotLoginException.class})
    public WebResponse handleBusinessNotLoginException(BusinessException ex) {
        log.error("Got BusinessException [{}]", ex.getMessage(), ex);
        return new WebResponse(ex.getErrorCode().getCode(), ex.getErrorCode().getMsg());
    }

    @ExceptionHandler({BusinessException.class})
    public WebResponse handleBusinessException(BusinessException ex) {
        log.error("Got BusinessException [{}]", ex.getMessage(), ex);
        return new WebResponse(ex.getErrorCode().getCode(), StringUtils.isNotBlank(ex.getMessage()) ? ex.getMessage() : ex.getErrorCode().getMsg());
    }

    @ExceptionHandler({Exception.class})
    public WebResponse handleException(Exception ex) {
        log.error("Go unhandled exception: ", ex);
        return new WebResponse("" + HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage());
    }

    @ExceptionHandler({RuntimeException.class})
    public WebResponse handleRuntimeException(RuntimeException ex) {
        log.error("Got RuntimeException [{}] ", ex.getMessage(), ex);
        return new WebResponse("" + HttpStatus.BAD_REQUEST.value(), ex.getMessage());
    }

//    @ExceptionHandler({MethodArgumentNotValidException.class})
//    public WebResponse handleArgumentNotValidException(MethodArgumentNotValidException ex) {
//        log.error("Go MethodArgumentNotValidException: ", ex);
//        List<ObjectError> objectErrors = Optional.ofNullable(ex.getBindingResult()).map(Errors::getAllErrors).orElse(Lists.newArrayList());
//        String errorMsg = objectErrors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(";\n"));
//        return new WebResponse("" + HttpStatus.INTERNAL_SERVER_ERROR, errorMsg);
//    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public WebResponse handleException(MethodArgumentNotValidException ex) {
        log.error("Got unhandled exception: [{}]", ex.getMessage(), ex);
        BindingResult exceptions = ex.getBindingResult();
        // 判断异常中是否有错误信息，如果存在就使用异常中的消息，否则使用默认消息
        List<String> errList = new ArrayList<>();
        if (exceptions.hasErrors()) {
            List<ObjectError> errors = exceptions.getAllErrors();
            if (!errors.isEmpty()) {
                for (ObjectError error : errors) {
                    // 这里列出了全部错误参数，按正常逻辑，只需要第一条错误即可
                    FieldError fieldError = (FieldError) error;
                    errList.add(fieldError.getDefaultMessage());
                }
            }
        }
        return WebResponse.build(ErrorCode.PARAM_ERROR.getCode(), errList.stream().collect(Collectors.joining("; ")));
    }
}
